﻿//==============================================================================
// File: TreeListView.cs
// Created: 2010-05-28
// Author: Piotr Włodek, Arek Świerczek
//==============================================================================
// This file is a part of MAMMOTH project.
// Copyright (C) 2010 AGH University of Science and Technology, Krakow.
// https://caribou.iisg.agh.edu.pl/trac/mammoth
//
// Mammoth is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// Mammoth is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public License
// along with Mammoth. If not, see http://www.gnu.org/licenses/.
//==============================================================================

using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Controls.Primitives;

namespace WpfRcp.Controls
{
    /// <summary>
    /// Represents a control that displays hierarchical data in a tree structure
    /// that has items that can expand and collapse.
    /// </summary>
    public class TreeListView : TreeView
    {
        public static RoutedCommand ExpandAllCommand = new RoutedCommand("ExpandAll", typeof(TreeListView));
        public static RoutedCommand CollapseAllCommand = new RoutedCommand("CollapseAll", typeof(TreeListView));

        public static readonly DependencyProperty SortPropertyNameProperty =
            DependencyProperty.RegisterAttached("SortPropertyName", typeof(string), typeof(TreeListView), new UIPropertyMetadata(null));
        
        public static readonly DependencyProperty SortableProperty =
            DependencyProperty.RegisterAttached("Sortable", typeof(bool), typeof(TreeListView), new UIPropertyMetadata(true));

        static TreeListView()
        {
            //Override the default style and the default control template
            DefaultStyleKeyProperty.OverrideMetadata(typeof(TreeListView), new FrameworkPropertyMetadata(typeof(TreeListView)));
        }

        /// <summary>
        /// Initialize a new instance of TreeListView.
        /// </summary>
        public TreeListView()
        {
            Columns = new GridViewColumnCollection();
            CommandBindings.Add(new CommandBinding(ExpandAllCommand, ExecuteExpandAllCommand, CanExecuteExpandAllCommand));
            CommandBindings.Add(new CommandBinding(CollapseAllCommand, ExecuteCollapseAllCommand, CanExecuteCollapseAllCommand));
        }

        private static void ExecuteExpandAllCommand(object sender, ExecutedRoutedEventArgs e)
        {
            var treeListView = (TreeListView)sender;
            treeListView.ExpandAll();
        }

        private static void CanExecuteExpandAllCommand(object sender, CanExecuteRoutedEventArgs e)
        {
            var treeListView = (TreeListView)sender;
            e.CanExecute = treeListView.Items.Count > 0;
        }

        private static void ExecuteCollapseAllCommand(object sender, ExecutedRoutedEventArgs e)
        {
            var treeListView = (TreeListView)sender;
            treeListView.CollapseAll();
        }

        private static void CanExecuteCollapseAllCommand(object sender, CanExecuteRoutedEventArgs e)
        {
            var treeListView = (TreeListView)sender;
            e.CanExecute = treeListView.Items.Count > 0;
        }

        #region Properties

        /// <summary>
        /// Gets or sets the collection of System.Windows.Controls.GridViewColumn 
        /// objects that is defined for this TreeListView.
        /// </summary>
        public GridViewColumnCollection Columns
        {
            get { return (GridViewColumnCollection)GetValue(ColumnsProperty); }
            set { SetValue(ColumnsProperty, value); }
        }

        /// <summary>
        /// Gets or sets whether columns in a TreeListView can be
        /// reordered by a drag-and-drop operation. This is a dependency property.
        /// </summary>
        public bool AllowsColumnReorder
        {
            get { return (bool)GetValue(AllowsColumnReorderProperty); }
            set { SetValue(AllowsColumnReorderProperty, value); }
        }

        public static string GetSortPropertyName(DependencyObject obj)
        {
            return (string)obj.GetValue(SortPropertyNameProperty);
        }

        public static void SetSortPropertyName(DependencyObject obj, string value)
        {
            obj.SetValue(SortPropertyNameProperty, value);
        }

        public static bool GetSortable(DependencyObject obj)
        {
            return (bool)obj.GetValue(SortableProperty);
        }

        public static void SetSortable(DependencyObject obj, bool value)
        {
            obj.SetValue(SortableProperty, value);
        }

        #endregion

        #region Static Dependency Properties

        public static readonly DependencyProperty AllowsColumnReorderProperty =
            DependencyProperty.Register("AllowsColumnReorder", typeof(bool), typeof(TreeListView), new UIPropertyMetadata(null));

        public static readonly DependencyProperty ColumnsProperty =
            DependencyProperty.Register("Columns", typeof(GridViewColumnCollection),
                                        typeof(TreeListView),
                                        new UIPropertyMetadata(null));
        #endregion

        protected override void OnInitialized(EventArgs e)
        {
            AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(GridViewColumnHeaderClickedHandler));

            base.OnInitialized(e);
        }

        private void GridViewColumnHeaderClickedHandler(object sender, RoutedEventArgs e)
        {
            var headerClicked = e.OriginalSource as GridViewColumnHeader;
            ICollectionView dataView = CollectionViewSource.GetDefaultView(ItemsSource);

            if (headerClicked != null && dataView != null && headerClicked.Column != null)
            {
                using (dataView.DeferRefresh())
                {
                    string sortProperty = GetSortPropertyName(headerClicked.Column);
                    bool isSortable = GetSortable(headerClicked.Column);
                    ListSortDirection direction;

                    //Checking if same column was clicked once again to reverse sorting order
                    if (dataView.SortDescriptions.Count > 0 && dataView.SortDescriptions[0].PropertyName == sortProperty)
                    {
                        direction = dataView.SortDescriptions[0].Direction == ListSortDirection.Ascending
                                        ? ListSortDirection.Descending
                                        : ListSortDirection.Ascending;
                    }
                    else
                    {
                        direction = ListSortDirection.Ascending;
                    }

                    // Removing previous sorting by same column
                    foreach (var sortDescription in dataView.SortDescriptions)
                    {
                        if (sortDescription.PropertyName == sortProperty)
                        {
                            dataView.SortDescriptions.Remove(sortDescription);
                            break;
                        }
                    }

                    // Sorting
                    if (!string.IsNullOrEmpty(sortProperty) && isSortable)
                    {
                        var sd = new SortDescription(sortProperty, direction);
                        dataView.SortDescriptions.Insert(0, sd);
                    }
                }
            }
        }
    }

    /// <summary>
    /// Represents a control that can switch states in order to expand a node of a TreeListView.
    /// </summary>
    public class TreeListViewExpander : ToggleButton { }

    /// <summary>
    /// Represents a convert that can calculate the indentation of any element in a class derived from TreeView.
    /// </summary>
    public class TreeListViewConverter : IValueConverter
    {
        private const double Indentation = 15;

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            //If the value is null, don't return anything
            if (value == null) return null;
            //Convert the item to a double
            if (targetType == typeof(double) && typeof(DependencyObject).IsAssignableFrom(value.GetType()))
            {
                //Cast the item as a DependencyObject
                var element = value as DependencyObject;
                
                //Create a level counter with value set to -1
                int level = -1;
                
                //Move up the visual tree and count the number of TreeViewItem's.
                for (; element != null; element = VisualTreeHelper.GetParent(element))
                    //Check whether the current elemeent is a TreeViewItem
                    if (typeof(TreeViewItem).IsAssignableFrom(element.GetType()))
                        //Increase the level counter
                        level++;
                //Return the indentation as a double
                return Indentation * level;
            }
            //Type conversion is not supported
            throw new NotSupportedException(
                string.Format("Cannot convert from <{0}> to <{1}> using <TreeListViewConverter>.",
                              value.GetType(), targetType));
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }

        #endregion
    }

    public class TreeListViewSortMultiConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            var treeListView = values[1] as TreeListView;

            if (treeListView != null)
            {
                ICollectionView currentDataView = CollectionViewSource.GetDefaultView(values[0]);
                ICollectionView itemsSourceDataView = CollectionViewSource.GetDefaultView(treeListView.ItemsSource);

                if (currentDataView != null && itemsSourceDataView != null)
                {
                    using(currentDataView.DeferRefresh())
                    {
                        //Copying sort descriptions from main ItemsSource
                        currentDataView.SortDescriptions.Clear();
                        foreach (var sortDescription in itemsSourceDataView.SortDescriptions)
                        {
                            currentDataView.SortDescriptions.Add(sortDescription);
                        }
                    }
                }

                return currentDataView;
            }
            return values[0];
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }
}